package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
)

// 获取会员收入信息
func GetUserIncomeInfo(p map[string]interface{}) *models.UserIncome {
	o := orm.NewOrm()
	userIncome := &models.UserIncome{}
	qs := o.QueryTable("UserIncome")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(userIncome)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if userIncome.Id > 0 {
			userIncome.CreatedShow = userIncome.Created.Format("2006-01-02 15:04:05")
			userIncome.CreatedShowDate = userIncome.Created.Format("2006.01.02")
		}
	}
	return userIncome
}

// 添加会员收入信息
func AddUserIncome(input url.Values) (int64, error) {
	o := orm.NewOrm()
	userIncome := &models.UserIncome{}
	user := &models.User{}
	if _, ok := input["user_id"]; ok {
		user.Id = utils.Atoi64(input["user_id"][0])
		o.Read(user)
	}
	userIncome.User = user
	fromUser := &models.User{}
	if _, ok := input["from_user_id"]; ok {
		fromUser.Id = utils.Atoi64(input["from_user_id"][0])
		o.Read(fromUser)
	}
	userIncome.FromUser = fromUser
	papPayApplyRecord := &models.PapPayApplyRecord{}
	if _, ok := input["pap_pay_apply_record_id"]; ok {
		papPayApplyRecord.Id = utils.Atoi64(input["pap_pay_apply_record_id"][0])
		o.Read(papPayApplyRecord)
	}
	userIncome.PapPayApplyRecord = papPayApplyRecord
	if _, ok := input["amount"]; ok {
		userIncome.Amount = utils.Atof64(input["amount"][0])
	}
	return o.Insert(userIncome)
}

// 修改会员收入信息
func EditUserIncome(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("UserIncome").Filter("id", input["id"][0]).Update(p)
}

// 获取会员收入列表
func GetUserIncomeList(p map[string]interface{}) (int64, []*models.UserIncome) {
	var userIncomeList []*models.UserIncome
	o := orm.NewOrm()
	qs := o.QueryTable("UserIncome")
	if _, ok := p["userId"]; ok {
		qs = qs.Filter("user_id", p["userId"])
	}
	if _, ok := p["createdDate"]; ok {
		qs = qs.Filter("created_date", p["createdDate"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&userIncomeList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, userIncome := range userIncomeList {
			userIncome.CreatedShow = userIncome.Created.Format("2006-01-02 15:04:05")
			userIncome.CreatedShowDate = userIncome.Created.Format("2006.01.02")
		}
	}
	return totalCount, userIncomeList
}